<template>
	<div class="herbherb-detail-page">
		<div class="herbherb-cont page-cont-box">
			<BreadCrumb :data="dataObj.crumbList" />
			
			<div class="cont-box">
				<div class="top-box">
					<div class="condition-box">
						<div class="condition-left">
							<CombinationSearch
								:searchObjList="searchObjList.searchObjArr"
								@removeSearchCond="removeSearchCond"
								@addSearchCond="addSearchCond"
								@reset="reset"
								@searchResult="searchResult"
								@searchInput="searchInput"
								@toGetSearch="toGetSearch"
							/>
						</div>
					</div>
				</div>

				<!-- 1 -->
				<div class="plane-box">
					<div class="title-box">
						<TitleBox>
							<template #titlecont>
								<span class="label-link-txt" v-lang="{lang: controlSto.language, lgid: -125}">Herb</span>
								<!-- <span class="label-link-txt">-</span>
								<span v-lang="{lang: controlSto.language, lgid: -19}">Herb</span> -->
							</template>
						</TitleBox>

					</div>
					<div>
						<CombinationDiagram
							:dragramTypeList="dragramTypeList"
							@changeTabs="changeTabs"
							:selectTab="selectTab"
							:diagramLenList="dataGraph.diagramLenList"
							@changeShow="changeShow"
							:typeGraph="1"
							:graphRange="graphRange"
							@changeSlider="changeSlider"
							:maxRange="maxRange"
							:dataGraph="dataGraph.data"
							:linksGraph="dataGraph.links"
							:dataTable="dataTable"
							:uiCodeDowm="uiCodeDowm"
							:dbData="dbData"
							:hotMapX="dataGraph.hotMapX"
							:hotMapY="dataGraph.hotMapY"
							:hotMapData="dataGraph.hotMapData"
							:hotMaxRange="dataGraph.hotMaxRange"
							:templateList="dataTable.templateList"
							@toClkItem="toClkItem"
							:para="dataTable.para"
							:condPage="condPage"
							@chgSize="chgSize"
							@chgCurrnt="chgCurrnt"
							:loading="isLoading"
							:loadingNetWork="dataObj.loadingNetWork"
							:noDataFlag="dataObj.noDataFlag"
						/>
					</div>
				</div>	
			</div>
		</div>

    </div>
</template>



<script setup>
    import { ref, reactive, computed, onBeforeMount, onMounted, nextTick, watch } from 'vue'
    import BreadCrumb from '@/components/BreadCrumb.vue'
    import TitleBox from '@/components/TitleBox.vue'
		import CombinationSearch from '@/components/CombinationSearch.vue'
		import CombinationDiagram from '@/components/combinationDiagram.vue'
		import { useRouter } from 'vue-router'
    import { controlStore } from '@/stores/control'
		import { cloneDeep } from 'lodash';
    import { langTxt, getFilterThArr, getFilterLangArr } from '@/utils/util'
		import { graph, heatmapdata, xLand, yLand, nData } from '@/utils/datagraph'
		import { getHerbherb, getTableThList, herbHerbNetworkTable, herbAll } from '@/service/tcm'


	const controlSto = controlStore();
	const router = useRouter();
	const selectTab = ref(0);
	const graphRange = ref([0, 40])
	const maxRange = ref(2415);
	const dbData = ref(nData)
	const isLoading = ref(false);
	const uiCodeDowm = ref('herb_herb_networtk');
	const uiCode = ref('overall_network'); //下载表格的code
	let dataGraph = reactive({
			data: [],
			links: [],
			diagramLenList: [],
			hotMapX: [],
			hotMapY: [],
			hotMapData: [],
			hotMaxRange: 2415
		});
		let condPage = reactive({
			pageSize: 10,
			pageNo: 1,
			total: 0
		})
		let dataObj = reactive({
		crumbList: [
            {
								fkey: '-16',
                lable: 'Home',
                name: 'home'
            }, {
								fkey: '-125',
								// skey: '-19',
                lable: 'Herb-Herb',
                name: ''
            }
        ],
				targetNameObj: [],
				sourceNameObj: []
	});
		const dataTable = reactive({
			filterKey: 'herbherb_netwrok',
			dTablevt: 1,
			tableConfig: {
				'tooltip-effect': 'dark',
				'highlight-current-row': true,
				stripe: true,
				'header-cell-style': { background: '#BC9F77', color: '#FFF' },
			},
			columnConfig: [],
			dataList: [],
			templateList: [{
					idField: '100716826576557300'
				}, 
				{
					idField: '100716826576557301'
				},
				{
					idField: '100716826576557302'
				},
				{
					idField: '100716826576557303'
				},
			],
			para: {
					langCode:controlSto.language == 1 ? 'ENG': 'CHN',
					// prescriptionId: detailId,
					uiTypeCode: uiCode.value,
					sourceName: dataObj.sourceNameObj,
					targetName: dataObj.targetNameObj
				},
				noDataFlag: true,
				loadingNetWork: false
		})
	
	let searchObjList = reactive({code: 'herb-herb', searchObjArr: []})
	let searchObjOrigin = reactive({
		maxSize: 19,
		defaultSize: 2,
		combinateOringin: 'Herb',
		combinationTo: 'Herb',
		combinateOringinlgid: '-19',
		combinationTolgid: '-19',
		seachCon: '',
		seachCode: '',
		opt: '2',
		id: '5',
		originData: [],
		targetData: [],
		originPlaceholder: "Coptis chinensis 黄连 huanglian",
		targetPlaceholder: 'Coptis chinensis 黄连 huanglian'
	})
	const dragramTypeList = [
		{
			tname: 'Network',
			lgid: '-60',
			code: 'Network'
		}, {
			tname: 'Heatmap',
			lgid: '-61',
			code: 'Heatmap'
		}, {
			tname: 'Table',
			lgid: '-62',
			code: 'Table'
		}
	]
	const diagramLenList = reactive([
		{
			source: {
				name: "Herb",
				code: 2
			},
			target: {
				name: "Herb",
				code: 2
			},
			id: 101,
			isShow: true
		},{
			source: {
				name: "Herb",
				code: 2
			},
			target: {
				name: "Ingedient",
				code: 3
			},
			id: 102,
			isShow: true
		}, {
			source: {
				name: "Ingedient",
				code: 3
			},
			target: {
				name: "Ingedient",
				code: 3
			},
			id: 103,
			isShow: true
		}
	])
	onBeforeMount(()=> {
		getHerbAll();
		getTableTh();
		getDataList();
		getSearchList();
	});
	onMounted(()=>{
		if (router.currentRoute.value.query.sname) getHerbAll(router.currentRoute.value.query.sname, 0, 2);
		if (router.currentRoute.value.query.tname) getHerbAll(router.currentRoute.value.query.tname, 1, 2);
		searchResult();
	});
	const changeSlider = (e) => {
		graphRange.value = e;
	}
	const changeShow = (item, index, isShow) => {
		// item.isShow = !item.isShow;
		diagramLenList[index].isShow = isShow;
	}
	const removeSearchCond = (item, index) => {
		if (index > 1) {
			searchObjList.searchObjArr.splice(index, 1)
		}
	}
	const addSearchCond = (item, index) => {
		searchObjList.searchObjArr.push(cloneDeep(searchObjOrigin))
	}
	const getSearchList = () => {
		  if(Object.values(searchObjOrigin).length !== 0) {
				for(let i = 0; i <= searchObjOrigin.defaultSize; i++) {
					searchObjOrigin.id = 'code_' + Math.random(9999) + Math.random(9999);
					searchObjList.searchObjArr.push(cloneDeep(searchObjOrigin))
				}
			}
	}
	const reset = () => {
		for(let v = 0; v < searchObjList.searchObjArr.length; v++) {
			searchObjList.searchObjArr[v].opt = '1';
			searchObjList.searchObjArr[v].seachCon = '';
		}
		dataObj.targetNameObj = [];
		dataObj.sourceNameObj = [];
		// searchResult();
		dataGraph = {
			data: [],
			links: [],
			diagramLenList: [],
			hotMapX: [],
			hotMapY: [],
			hotMapData: [],
			hotMaxRange: 2415,
			dbData: []
		}
		condPage = {
			pageSize: 10,
			pageNo: 1,
			total: 0
		}
		dataTable.dataList = [];
	}
	const searchResult = () => {
		let targetNameArr = [], sourceNameArr = [];
		searchObjList.searchObjArr.forEach((e, index) => {
			if (index && e.seachCon && e.seachCode) {
				// targetNameObj[e.seachCode] = e.opt
				targetNameArr.push(e.seachCode)
			} else if (e.seachCode) {
				// sourceNameObj[e.seachCode] = e.opt
				sourceNameArr.push(e.seachCode)
			}
		})
		dataObj.targetNameObj = targetNameArr;
		dataObj.sourceNameObj = sourceNameArr.join(',');
		dataTable.para.sourceName = sourceNameArr.join(',');
		dataTable.para.targetName = targetNameArr;
		getDataList();
		// getTableData();
	}
	const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});

	const toClkItem = (rowItem, index) => {
		if (!index && index == 1) {
			//herb
			router.push({ name: 'herbdetail', query: {id: rowItem[dataTable.templateList[0].idField]} });
		} else {
			//成分
			router.push({ name: 'ingrdetail', query: {id: rowItem[dataTable.templateList[2].idField]} });
		}
	}
	// -------1-----------------------------------------------------------------
	const searchInput = (name, index) => {
		getHerbAll(name, index, 1)
	}

	const toGetSearch = (code, name, index) => {
		searchObjList.searchObjArr[index].seachCon = name;
		searchObjList.searchObjArr[index].seachCode = code;
	}
	const getHerbAll = (name, index, type) => {
		herbAll({
			langCode: controlSto.language == 1 ? 'ENG' : "CHN",
			name: name || ''
		}).then(res => {
			if(res.success && res.data) {
				if (type == 1) {
					searchObjList.searchObjArr[index].targetData = res.data;
					searchObjList.searchObjArr[index].originData = res.data;
				} else if (type ==  2) {
					searchObjList.searchObjArr[index].targetData = res.data;
					searchObjList.searchObjArr[index].originData = res.data;
					searchObjList.searchObjArr[0].seachCon = router.currentRoute.value.query.sname;
					searchObjList.searchObjArr[1].seachCon = router.currentRoute.value.query.tname;
					res.data.forEach(e => {
						if(index && e.name == router.currentRoute.value.query.tname) {
							searchObjList.searchObjArr[index].seachCode = e.code;
						}
						if(!index && e.name == router.currentRoute.value.query.sname) {
							searchObjList.searchObjArr[index].seachCode = e.code;
						}
					})
					searchResult();
				} else{
					searchObjOrigin.originData = res.data || [];
					searchObjOrigin.targetData = res.data || [];
					searchObjList.searchObjArr.forEach(e => {
						e.targetData = res.data;
						e.originData = res.data;
					})
				}
			}
		})
	}

	const getTableTh = () => {
        getTableThList({
					uiCode: uiCode.value,
          langCode: 'ENG,CHN'
				}).then((res) => {
            isLoading.value = false;
            if (res.success) {
              let arr = res.data || [];
							let thArr = getFilterThArr(arr, dataTable.filterKey);
							let langArr = getFilterLangArr(thArr);
							controlSto.setLangList(langArr);
							dataTable.columnConfig = thArr;
							// console.log(dataTable.columnConfig, 'ataTable.columnConfig==')
            }
        }).catch(() => {
            isLoading.value = false;
        });
    };

	
    const getDataList = () => {
			if(dataObj.sourceNameObj.length == 0 || dataObj.targetNameObj.length == 0) return;
			dataObj.loadingNetWork = true;
			getHerbherb({
				langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
				sourceName: dataObj.sourceNameObj,
				targetName: dataObj.targetNameObj,
				uiTypeCode: uiCode.value
			}).then(res => {
				const resp = res.data;
				if (resp.success && resp.data) {
					dataObj.loadingNetWork = false;
					if (resp.data.scatterDiagram) {
						const scatterDiagram = resp.data.scatterDiagram;
						if(scatterDiagram.nodeList.length == 0) dataObj.noDataFlag = true;
						else dataObj.noDataFlag = false;

						if (scatterDiagram.links && scatterDiagram.nodeList) {
							let arrXy = [], xyData = [];
							scatterDiagram.links.forEach((e, indx) => {
								if (!indx) {
									maxRange.value = Number(e.distance);
								} else if (maxRange.value < Number(e.distance )) maxRange.value = Number(e.distance);
								graphRange.value = [0, maxRange.value];
								dataGraph.hotMaxRange = maxRange.value;
								// dataGraph.hotMaxRange = 2415;
								scatterDiagram.nodeList.forEach((o, index) => {
									arrXy.push(o.name)
									if (e.source == o.id) e.sourceCategory = o.category;
									if (e.target == o.id) e.targetCategory = o.category;
									o.symbolSize = 10;
									// if (o.category == 2) {
									// 		o.symbolSize = 20;
									// 	} else if (o.category == 3) {
									// 		o.symbolSize = 15
									// 	}
									if (!index) {
										o.y = (e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(120) + 3)));
										o.x = -(e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(120) + 5)));
									}
									if (!o.x && index) {
										o.y = (e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(index) + index)));
										o.x = -(e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(index) + index)));
									}
									//线的颜色
									if (e.source ==  o.id && o.category == 2) {
											e.lineStyle = {
												color: '#138848',
												width: 1
											}
									} else if (e.source ==  o.id && o.category == 3) {
										e.lineStyle = {
											color: '#1677FF',
											width: 1
										} 
									} else if (e.source ==  o.id && o.category == 1) {
										e.lineStyle = {
											color: '#BC9F77',
											width: 1
										}
									} else if (e.source ==  o.id && o.category == 4) {
										e.lineStyle = {
											color: '#02BCD5',
											width: 1
										}
									}
									//元素的颜色
									if (o.category == 2) {
											o.itemStyle = {
												color: '#138848'
											}
										} else if(o.category == 3) {
											o.itemStyle = {
												color: '#1677FF'
											}
										} else if(o.category == 1) {
											o.itemStyle = {
												color: '#BC9F77'
											}
										} else if(o.category == 4) {
											o.itemStyle = {
												color: '#02BCD5'
											}
										}
								})
							})
							dataGraph.data = scatterDiagram.nodeList;
							dataGraph.links = scatterDiagram.links;
							console.log('散点图数据', dataGraph.data, '散点图关系线', dataGraph.links)
							//处理heatmap数据；
							let _arrXy = new Set(arrXy)
							arrXy = [..._arrXy]
							arrXy.forEach((ex, xind) => {
								arrXy.forEach((ey, yind) => {
									let id1 = '', id2 = '';
									scatterDiagram.nodeList.forEach((enode, nodeind) => {
										if(ex == enode.name) id1 = enode.id;
										if(ey == enode.name) id2 = enode.id;
										
									})
									if (id1 && id2){
										scatterDiagram.links.forEach((elink, linkInd)=> {
											if (id1 == elink.source && elink.target == id2) {
												xyData.push([xind, yind, Number(elink.distance)])
												id1 = '';
												id2 = '';
											}
										})
									}
								})
							});
							dataGraph.hotMapData = xyData;
							dataGraph.hotMapX = arrXy.reverse();
							dataGraph.hotMapY = arrXy;
						}
						console.log('热力图数据', dataGraph.hotMapData, '热力图横纵坐标', dataGraph.hotMapX)
						if(scatterDiagram.contractlist) {
							//diagramLenList
							scatterDiagram.contractlist.forEach((e, index) => {
								e.isShow = true;
								e.id = 'pre_' + index;
								e.source = {
									code: e.sourceCategory,
									name: e.sourceName
								}
								e.target = {
									code: e.targetCategory,
									name: e.targetName
								}
							});
							dataGraph.diagramLenList = scatterDiagram.contractlist
						}
					}
					getTableData();
				}
			}).catch((err) => {
				dataObj.noDataFlag = true;
				dataObj.loadingNetWork = false;
			})

        
    };
		const getTableData = () => {
			isLoading.value = true;
			herbHerbNetworkTable({
				langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
				sourceName: dataObj.sourceNameObj,
				targetName: dataObj.targetNameObj,
				uiTypeCode: uiCode.value,
				pageSize: condPage.pageSize,
				pageNo: condPage.pageNo
			}).then(res => {
				const _res = res.data;
				if (_res.success && _res.data.records) {
					isLoading.value = false;
					dataTable.dataList = _res.data.records || [];
					condPage.total = _res.data.totalCount || 0;
				}
			}).catch(err => {
				isLoading.value = false;
			})
	}
	const chgSize = (e) => {
		condPage.pageSize = e || 10;
    getTableData();
	}
	const chgCurrnt = (e) => {
		condPage.pageNo = e || 1;
    getTableData();
	}
	const changeTabs = (item, index) => {
		selectTab.value = index
		if(index == 0) {
			//关系图
			dataGraph.diagramLenList.forEach(e => {
				e.isShow = true;
			})
		} else if (index == 1) {
			//热力图
		} else if (index == 2) {
			//table
		}
	}
	watch(() => controlSto.language, (nv, ov) => {
			if(nv != ov) {
				getHerbAll();
				getDataList();
				getTableData();
			}
		});
</script>

<style lang="scss" scoped>
	.herbherb-detail-page {
		height: 100%;
		min-height: calc(100vh - 250px);
		text-align: center;
		background-size: 100% 100%;
		.herbherb-cont {
			display: inline-block;
			// width: 1400px;
    		text-align: left;
			.title-box {
				padding-bottom: 32px;
			}
			.switch-box {
				padding-bottom: 32px;
				text-align: center;
				.switch-wrap {
					display: inline-block;
					border: 1px solid #BC9F77;
					border-radius: 30px;
					font-size: 0;
					color: #967846;
					.switch-item {
						display: inline-block;
						height: 40px;
						width: 200px;
						padding: 0 32px;
						line-height: 40px;
						border-right: 1px solid #BC9F77;
						font-weight: 600;
						font-size: 18px;
						cursor: pointer;
						&:first-child {
							// border-radius: 30px;
							border-top-left-radius: 16px;
							border-bottom-left-radius: 16px;
						}
						&:last-child {
							border-right: none;
							border-top-right-radius: 16px;
							border-bottom-right-radius: 16px;
						}
						&.switch-item-on {
							color: #fff;
							background-color: #BC9F77;
						}
					}
				}

			}
			.condition-box {
				// padding-bottom: 32px;
				.cond-item {
					margin-right: 16px;
				}
			}

			.cont-box {
				.plane-box {
					padding: 32px 0;
				}
			}



		}
	}
	
</style>




<style lang="scss">
    .cond-item-drop-box {
        .cond-drop-cont-wrap {
			max-height: 260px;
			overflow-y: auto;
			.cond-wrap {
				width: 188px;
				.cond-item-select {
					// width: 188px;
					padding: 8px 16px;
					margin-right: 0;
					font-size: 14px;
					font-weight: 400;
					border-bottom: 1px solid #ddd;
					cursor: pointer;
					&:last-child {
						border-bottom: none;
					}
				}
			}
        }
    }
</style>